<template>
  <lay-card width="1200" style="height: 950px">
      <lay-row space="20">
        <lay-col md="24">
          <lay-quote size="sm">
            <h3>用例上的配置编辑</h3>
          </lay-quote>
        </lay-col>
      </lay-row>
     <lay-row space="20">
        <lay-col md="6">
          <lay-input
              v-if="addFlag"
              v-model="project"
              placeholder="请输入名称"
              style="width: 100%"
              label="项目名称"
          >
            <template #prepend>项目名称</template>
          </lay-input>
          <lay-select
              v-else
              v-model="project"
              placeholder="请选择项目"
              style="width: 100%"
              label="项目名称"
          >
            <template #prepend>项目名称</template>
            <lay-select-option :value="unit" :label="unit" v-for="unit in projects"></lay-select-option>
          </lay-select>
        </lay-col>
        <lay-col md="2">
          <lay-checkbox
              v-if="method === 'config'"
              style="margin-top: 5px"
              value="1"
              v-model="addFlag"
              @change="modifyProject"
          >是否新增</lay-checkbox>
        </lay-col>
        <lay-col md="6">
          <lay-button type="normal" @click="queryConfig">查询</lay-button>
          <lay-button type="normal" @click="saveConfig" v-if="method === 'config'">保存</lay-button>
        </lay-col>
     </lay-row>
     <lay-row space="20">
        <lay-col md="24">
          <lay-tab v-model="method" type="brief">
            <lay-tab-item title="查看" id="query">
              <lay-table
                  :height="'600px'"
                  ref="tableRef"
                  :columns="columns"
                  :data-source="dataSource"
                  :default-toolbar="false"
              >
                <template v-slot:caseName="{ row }">
                  <a @click="downLoadDataMethod(row)" v-if="row.url===''">{{row.caseName}}</a>
                  <a @click="downLoadDataMethod(row)" style="color: blue;" v-else>{{row.caseName}}</a>
                </template>
              </lay-table>
            </lay-tab-item>
            <lay-tab-item title="编辑" id="config">
              <lay-textarea v-model="configData" style="height: 500px"></lay-textarea>
            </lay-tab-item>
          </lay-tab>
        </lay-col>
      </lay-row>
  </lay-card>
</template>

<script lang="ts">

export default {
  name: 'ConfigEdit',
  components: {
  }
}

</script>

<script lang="ts" setup>
import {onMounted, reactive, ref} from "vue";
import {downExcelFile, queryConfigApi, queryProjects, saveConfigApi} from "../../../api/fastApi/fastApi";
import {notify} from "../../../untils/tip";
import {layer} from "@layui/layer-vue";


onMounted(()=>{
    queryProjectsApi();
    // initEditor();
})

const method = ref('query');
const configData = ref('')
const project = ref('金融反洗钱项目');
const projects = ref([]);
const editor = ref();
const addFlag: any = ref<boolean>(false);

const dataSource = ref([]);
const columns = ref([
      {
        fixed: "left",
        width:"15%",
        title: "用例类型(标准模板)",
        key: "caseName",
        customSlot:"caseName"
      },
      {
        title:"步骤匹配正则",
        width:"15%",
        key:"stepPattern"
      },
      {
        title:"前置提取入参",
        width:"10%",
        key:"preconditions"
      },
      {
        title:"备注提取入参",
        width:"10%",
        key:"remark"
      },
      {
        title:"输入数据提取",
        width:"20%",
        key:"inputPattern"
      },
      {
        title:"预期结果提取",
        width:"20%",
        key:"expectPattern"
      },
      {
        title:"期望后缀",
        width:"5%",
        key:"expectKey"
      },
      {
        title:"Blade上的脚本名称",
        width:"15%",
        key:"scriptName"
      },
    ])

const modifyProject = () => {
  if(addFlag){
    project.value = ''
  }
}

const downLoadDataMethod = async (unit: any) => {
  console.log("downLoadData：", unit)
  const filename = unit?.caseName;
  try {
    if(unit?.url === ""){
      notify('failed', filename + '暂无标准示例模板！')
    }else {
      const response = await downExcelFile(unit);
      const url = window.URL.createObjectURL(new Blob([response]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', filename + '_标准用例模板.xlsx');
      document.body.appendChild(link);
      link.click();
      notify('success', filename + '的标准模板下载成功！')
    }
  } catch (error) {
    console.error(error);
    notify('failed', filename + '的标准模板下载失败！')
  }
}

const setContent = (content) => {
  editor.value.setValue(content);
}

const queryConfig = async () => {
    let response = await queryConfigApi({project: project.value, method: method.value});
    if(response.status === 200){
      if(method.value === 'config'){
        configData.value = response.content;
        setContent(configData.value);
      }else {
        dataSource.value = response.content.ScriptPattern;
      }
    }
}

const queryProjectsApi = async () => {
    let response = await queryProjects({});
    if(response.status === 200){
        projects.value = response.result;
    }
}

const saveConfigMethod = async () => {
  const formData = new FormData();
  formData.append('project', project.value);
  formData.append('addFlag', addFlag.value);
  formData.append('content', configData.value);
  let response = await saveConfigApi(formData);
  if(response.status === 200){
      notify("success", response.message)
      await queryProjectsApi();
  }else {
      notify("failed", "保存失败！")
  }
}

const saveConfig = () => {
    layer.confirm("确定保存吗？不符合yaml格式会导致程序报错！",
        {
            btn: [
                {text:'确定', callback: (id) => {
                    saveConfigMethod();
                    layer.close(id); }
                },
                {text:'取消', callback: (id) => {
                    layer.close(id); }
                }
            ]
        }
    );
}

</script>


<style scoped>

</style>
